
package com.learn.spring.resource.to.doc.vo;


import com.learn.spring.beandefination.BeanDefinition;
import com.learn.spring.env.Environment;
import com.learn.spring.resource.loader.ResourceLoader;
import com.learn.spring.exceptions.BeanDefinitionStoreException;
import com.learn.spring.exceptions.handle.ProblemReporter;
import com.learn.spring.extractor.SourceExtractor;
import com.learn.spring.factory.features.BeanDefinitionRegistry;
import com.learn.spring.lang.Nullable;
import com.learn.spring.namespace.NamespaceHandlerResolver;
import com.learn.spring.resource.Resource;
import com.learn.spring.resource.to.doc.XmlBeanDefinitionReader;
import com.learn.spring.resource.to.doc.hook.ReaderEventListener;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import java.io.StringReader;



public class XmlReaderContext extends ReaderContext {

	private final XmlBeanDefinitionReader reader;

	private final NamespaceHandlerResolver namespaceHandlerResolver;




	public XmlReaderContext(
            Resource resource, ProblemReporter problemReporter,
            ReaderEventListener eventListener, SourceExtractor sourceExtractor,
            XmlBeanDefinitionReader reader, NamespaceHandlerResolver namespaceHandlerResolver) {

		super(resource, problemReporter, eventListener, sourceExtractor);
		this.reader = reader;
		this.namespaceHandlerResolver = namespaceHandlerResolver;
	}




	public final XmlBeanDefinitionReader getReader() {
		return this.reader;
	}



	public final BeanDefinitionRegistry getRegistry() {
		return this.reader.getRegistry();
	}



	@Nullable
	public final ResourceLoader getResourceLoader() {
		return this.reader.getResourceLoader();
	}



	@Nullable
	public final ClassLoader getBeanClassLoader() {
		return this.reader.getBeanClassLoader();
	}



	public final Environment getEnvironment() {
		return this.reader.getEnvironment();
	}



	public final NamespaceHandlerResolver getNamespaceHandlerResolver() {
		return this.namespaceHandlerResolver;
	}



	public String generateBeanName(BeanDefinition beanDefinition) {
		return this.reader.getBeanNameGenerator().generateBeanName(beanDefinition, getRegistry());
	}


	public String registerWithGeneratedName(BeanDefinition beanDefinition) {
		String generatedName = generateBeanName(beanDefinition);
		getRegistry().registerBeanDefinition(generatedName, beanDefinition);
		return generatedName;
	}

	/**
	 * Read an XML document from the given String.
	 * @see #getReader()
	 */
	public Document readDocumentFromString(String documentContent) {
		InputSource is = new InputSource(new StringReader(documentContent));
		try {
			return this.reader.doLoadDocument(is, getResource());
		}
		catch (Exception ex) {
			throw new BeanDefinitionStoreException("Failed to read XML document", ex);
		}
	}

}
